<?php


namespace App\Logic\Account\Form;

use App\Core\BaseListForm;
use App\Core\Exception\DefaultException;
use App\Event\Event;
use App\Logic\Account\CashoutService;
use App\Logic\Member\MemberScoreService;
use App\Model\Account\CashoutModel;
use App\Model\Member\MemberModel;
use App\Model\Member\MemberScoreModel;
use App\Util\CommonHelper;
use App\Util\UserIdentityHelper;
use EasySwoole\ORM\DbManager;

class SubmitCashoutForm extends BaseListForm
{
    public $id;
    public $user_id;
    public $score;
    public $payment_type;
    public $payment_content;
    public $created_at;
    public $_memberModel;
    /**
     * 校验规则 rules
     * @return array[]
     */
    public function rules()
    {
        return [
            'score'    => ['required|numeric', 'U', 'U错误'],
            'payment_type' => ['required', '提现方式', '提现方式错误'],
//            'payment_content' => ['required', '支付凭证', '支付凭证错误'],
        ];
    }
    public function validate()
    {
        //生成验证器，方法自动读取rules方法返回的值数据
        $validator = $this->createValidator();
        $validator->addColumn('payment_type')->inArray([CashoutModel::PAYMENT_USDT, CashoutModel::PAYMENT_PUB_BANK]);
        if (!($check = $validator->validate($this->getAttributes()))) {
            throw new DefaultException($validator->getError()->__toString(), 600);
        }
        if($this->score == 0){
            throw new DefaultException('提现金额必须大于0', 600);
        }

        /**判断当前日期是否可以提现*/
        if(!in_array(date('d'), CashoutModel::ALLOW_DATE)){
            throw new DefaultException('当前日期不允许提现', 600);
        }

        /**判断账户是否存在,账户中是否有足够的代币*/
        $this->user_id = UserIdentityHelper::getId();
        if(!$member = $this->getMember()){
            throw new DefaultException('账户不存在', 600);
        }
        /**判断提现金额是否超过最大可提现金额*/
        $maxCashoutAmount = CashoutService::getInstance()->getPrincipalAccountMaxCashoutAmount($this->user_id);
        if($maxCashoutAmount < bcmul($this->score, 1, 2)){
            throw new DefaultException('提现额度超过最大可提现额度(' . $maxCashoutAmount . ')', 600);
        }
        /**如果提现方式为CashoutModel::PAYMENT_USDT 并且member信息中usdt字段为空,则报错*/
        if($this->payment_type == CashoutModel::PAYMENT_USDT && empty($member->usdt)){
            throw new DefaultException('请先设置账户USDT信息', 600);
        }
        /**如果提现方式为CashoutModel::PAYMENT_WECHAT 并且member信息中wepay_qr字段为空,则报错*/
        if($this->payment_type == CashoutModel::PAYMENT_WECHAT && empty($member->wepay_qr)){
            throw new DefaultException('请先设置账户微信收款码', 600);
        }
        /**如果提现方式为CashoutModel::PAYMENT_ALIPAY 并且member信息中alipay_qr字段为空,则报错*/
        if($this->payment_type == CashoutModel::PAYMENT_ALIPAY && empty($member->alipay_qr)){
            throw new DefaultException('请先设置账户支付宝收款码', 600);
        }
        /**如果提现方式为CashoutModel::PAYMENT_PUB_BANK 并且member信息中pub_bank_name字段或pub_bank_deposit或pub_bank_account_name或pub_bank_account_no为空,则报错*/
        if($this->payment_type == CashoutModel::PAYMENT_PUB_BANK && (empty($member->pub_bank_name) || empty($member->pub_bank_deposit) || empty($member->pub_bank_account_name) || empty($member->pub_bank_account_no))){
            throw new DefaultException('请先设置账户公网银行卡信息', 600);
        }
        /**如果提现方式为CashoutModel::PAYMENT_PRI_BANK 并且member信息中pri_bank_name字段或pri_bank_deposit或pri_bank_account_name或pri_bank_account_no为空,则报错*/
        if($this->payment_type == CashoutModel::PAYMENT_PRI_BANK && (empty($member->pri_bank_name) || empty($member->pri_bank_deposit) || empty($member->pri_bank_account_name) || empty($member->pri_bank_account_no))){
            throw new DefaultException('请先设置账户私网银行卡信息', 600);
        }
        if(bcmul($member->score, 1, 2) < bcmul($this->score, 1, 2)){
            throw new DefaultException('账户余额不足', 600);
        }
        return true;
    }

    public function submit()
    {
        $this->validate();
        $member = $this->getMember();
        //插入数据
        DbManager::getInstance()->startTransactionWithCount('write');
        try {
            //添加表
            $insertData = [
                'user_id'               => $this->user_id,
                'amout'                 => $this->score,
                'service_fee'          =>  CashoutModel::SERVICE_FEE,
                'account_type'          => CashoutModel::ACCOUNT_TYPE_FUNDS,
                'cash_state'            => CashoutModel::INPROGRESS,
                'payment_type'          => $this->payment_type,
                'usdt'                  => $member->usdt,
                'wepay_qr'              => $member->wepay_qr,
                'alipay_qr'             => $member->alipay_qr,
                'pub_bank_name'         => $member->pub_bank_name,
                'pub_bank_deposit'      => $member->pub_bank_deposit,
                'pub_bank_account_name' => $member->pub_bank_account_name,
                'pub_bank_account_no'   => $member->pub_bank_account_no,
                'pri_bank_name'         => $member->pri_bank_name,
                'pri_bank_deposit'      => $member->pri_bank_deposit,
                'pri_bank_account_name' => $member->pri_bank_account_name,
                'pri_bank_account_no'   => $member->pri_bank_account_no
            ];

            //插入数据库
            $res = CashoutModel::insertData($insertData);
            $id  = $res->lastQueryResult()->getLastInsertId();

            MemberScoreService::getInstance()->change($this->user_id, bcmul($this->score, -1, 2), MemberScoreModel::TYPE_CASHOUT, $id,'提现代币(本金账户)');

//            /**MemberModel 通过$this->user_id获取到用户信息,并且lockForUpdate*/
//            $member = MemberModel::create()->connection('write')->lockForUpdate()->get($this->user_id);
//            /**将提现代币score更新到ss_member中 MemberModel*/
//            $memberData = [
//                'score' => bcsub($member->score, $this->score, 2),
//            ];
//            MemberModel::create()->updateData($memberData, ['id' => $this->user_id]);
//
//            /**MemberScoreModel 将score的变动记录添加到ss_member_score中*/
//            $data = [
//                'user_id'      => $this->user_id,
//                'score'        => bcmul($this->score, -1, 2),
//                'before_score' => $member->score,
//                'after_score'  => bcsub($member->score, $this->score, 2),
//                'created_date' => date('Y-m-d'),
//                'remark'       => '提现代币(本金账户)',
//                'type'         => MemberScoreModel::TYPE_CASHOUT,
//                'object_id'    => $id
//            ];
//            MemberScoreModel::create()->insertData($data);

            DbManager::getInstance()->commitWithCount('write');

            $returnData = ['id' => $id, 'score' => $this->score,];

            $result = $this->success($returnData);
            return $result;
        } catch (\Throwable $e) {
            DbManager::getInstance()->rollbackWithCount('write');
            CommonHelper::logException($e, '下单错误');
            throw $e;
        }
    }
    public function getMember()
    {
        if ($this->_memberModel === null) {
            $user_id = $this->user_id;
            $this->_memberModel = MemberModel::getOne(['id' => $user_id]);
        }
        return $this->_memberModel;
    }

}
